import type { App, Directive, DirectiveBinding } from "vue";

const clickOutside: Directive = {
  mounted: (el: any, binding: DirectiveBinding) => {
    function clickHandler(e: any) {
      console.log(el, e.target, el.contains(e.target));
      // 这里判断点击的元素是否是本身，是本身，则返回
      if (el.contains(e.target)) {
        return false;
      }
      binding.value(e);
    }
    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.__vueClickOutside__ = clickHandler;
    document.addEventListener("click", clickHandler);
  },
  unmounted: (el) => {
    // 解除事件监听
    document.removeEventListener("click", el.__vueClickOutside__);
    delete el.__vueClickOutside__;
  },
};

export function setupClickOutsideDirective(app: App) {
  app.directive("clickOutside", clickOutside);
}

export default clickOutside;
